package com.rain.shoppingscienceproj.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.MyMap;
import com.rain.shoppingscienceproj.module.MycolorArea;
import com.rain.shoppingscienceproj.module.UserInfo;
import com.rain.shoppingscienceproj.ui.activity.address.ShowAddressActivity;
import com.rain.shoppingscienceproj.ui.activity.car.ShoppingCarActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.activity.message.MessageActivity;
import com.rain.shoppingscienceproj.ui.activity.order.OrderListActivity;
import com.rain.shoppingscienceproj.ui.activity.search.SearchLocalityActivity;
import com.rain.shoppingscienceproj.ui.activity.setting.SettingActivity;
import com.rain.shoppingscienceproj.ui.activity.setting.UserInfoActivity;
import com.rain.shoppingscienceproj.ui.activity.shopping.ShoppingActivity;
import com.rain.shoppingscienceproj.ui.activity.shopping.ShoppingDetailsActivity;
import com.rain.shoppingscienceproj.ui.adapter.MainAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.ColorChangeHelp;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.PowerUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.ImageUtils;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.SharedPreferencesUtil;
import com.rain.shoppingscienceproj.utils.layoutmanager.item.SpaceItemDecoration;
import com.rain.shoppingscienceproj.utils.rxBus.RxBus;
import com.rain.shoppingscienceproj.utils.rxBus.RxBusSubscriber;
import com.rain.shoppingscienceproj.utils.rxBus.RxSubscriptions;
import com.rain.shoppingscienceproj.utils.sonic.SonicRuntimeImpl;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;


public class MainActivity extends BaseActivity {

    //    @BindView(R.id.map_view)
//    MyMapView myMapView;
    @BindView(R.id.drawer)
    DrawerLayout drawerLayout;
    @BindView(R.id.nav)
    NavigationView navigationView;
    @BindView(R.id.tv_title_main)
    TextView tv_title_main;
    @BindView(R.id.recycler_main)
    RecyclerView recyclerView;
    private MainAdapter adapter;


    private MyMap myMap;
    private HashMap<String, List<MycolorArea>> colorView_hashmap;
    ClipboardManager myClipboard;
    private String provinceId = "110000";
    private TextView tv_nickname;
    private TextView tv_sign;
    private ImageView iv_image_person;
    private long exitTime = 1000;
    private int isShow = 1;
    private String COPY = "shopping_science_goodsId_is";

    @OnClick(R.id.et_finding_search)
    void search() {
        startActivitys(SearchLocalityActivity.class, 1);
    }

    /*@OnClick(R.id.iv_car)
    void car() {
        startActivitys(ShoppingCarActivity.class);
    }*/


    @OnClick(R.id.message_iv)
    void message() {
        if (userInfo == null) {
            startActivitys(LoginActivity.class, 1);
            return;
        }
        startActivitys(MessageActivity.class);
    }

    @OnClick(R.id.rl_user)
    void nav() {
        if (drawerLayout.isDrawerOpen(navigationView)) {
            drawerLayout.closeDrawer(navigationView);
        } else {
            drawerLayout.openDrawer(navigationView);
        }
    }

    /*@OnClick(R.id.ll_shoping)
    void shop() {
//        if ("".equals(provinceId)) {
//            ToastUtils.showShortToast("请选择省份");
//            return;
//        }

    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        userInfo = GlobalData.getUserInfo();
        loadingDialog = new LoadingDialog(this, "正在加载...");
        initView();
        //设置颜色渐变条
        setColorView();

        initListener();
        String fonts = "fonts/heave.ttf";
        Typeface typeface = Typeface.createFromAsset(getAssets(), fonts);
        tv_title_main.setTypeface(typeface);

        clipData();

        sonic();
    }

    private void sonic() {

        if (hasPermission()) {
            init();
        } else {
            requestPermission();
        }
    }

    private void init() {
        // init sonic engine
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }
    }

    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }


    private void clipData() {
        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData abc = myClipboard.getPrimaryClip();
        if (abc != null) {
            ClipData.Item item = abc.getItemAt(0);
            String text = item.getText().toString();
            if (text != null) {
                if (text.contains(COPY)) {
                    String[] datas = text.split(":");
                    String goodsId = datas[1];
                    startActivitys(ShoppingDetailsActivity.class, goodsId);
                }
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        userInfo = GlobalData.getUserInfo();
        String tokens = userInfo.getToken();
        if (userInfo != null) {
            RetrofitClient.getInstance(this)
                    .createBaseApi()
                    .userInfo(userInfo.getUserId(), new BaseSubscriber<ResponseBody>(this) {
                        @Override
                        public void onError(ExceptionHandle.ResponeThrowable e) {
                            ToastUtils.showShortToast(e.Message);
                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            super.onNext(responseBody);
                            try {
                                String request = responseBody.string();
                                JSONObject json = new JSONObject(request);
                                int code = json.getInt("code");
                                if (code == 0) {
                                    JSONObject jsonData = json.getJSONObject("data");
                                    String jsonString = jsonData.getString("user");
                                    TypeToken<UserInfo> token = new TypeToken<UserInfo>() {
                                    };
                                    userInfo = new Gson().fromJson(jsonString, token.getType());
                                    userInfo.setUserId(userInfo.getId());
                                    userInfo.setToken(tokens);
                                    GlobalData.setUserInfo(userInfo);
                                    SharedPreferencesUtil.putString(MainActivity.this, "AppShopping", "AppShopping", new Gson().toJson(userInfo));
                                } else {
                                    ToastUtils.showShortToast(json.getString("msg"));
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
        isShow = 1;
    }

    private void initData() {
        if (userInfo == null) {
            tv_nickname.setText("暂未登录");
            return;
        }
        if (PowerUtils.isNotificationEnabled(this)) {
        } else {
            DialogUtils.dialog(this, "当前手机的通知栏未打开，为确保消息的正常接收请打开APP的通知");
            DialogUtils.getTv_sure().setOnClickListener(v -> goToSet());
        }
        RxSubscriptions.add(RxBus.getInstance().toObserverable(String.class).subscribe(new RxBusSubscriber<String>() {
            @Override
            protected void onEvent(String s) {
                if (s.equals("MessageServiceIntent")) {
                    if (isShow == 1) {
                        isShow++;
                        startActivitys(MessageActivity.class);
                    }
                }
            }
        }));

        if (null != userInfo.getAvatarurl() || !"".equals(userInfo.getAvatarurl())) {
            ImageUtils.imageCircle(MainActivity.this, userInfo.getAvatarurl(), iv_image_person);
        }
        tv_nickname.setText(userInfo.getNickname());
        tv_sign.setText(userInfo.getUsername());
//        dataProvince(provinceId);
    }

    private void goToSet() {
        DialogUtils.dismissDialog();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        }
    }

    private void initView() {

        View view = navigationView.inflateHeaderView(R.layout.head_layout);

        iv_image_person = view.findViewById(R.id.iv_image_person);

        tv_nickname = view.findViewById(R.id.tv_nickname);

        tv_sign = view.findViewById(R.id.tv_sign);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new MainAdapter(this);
//
        recyclerView.setAdapter(adapter);

    }

    private void initListener() {

        // 列表的点击事件
        adapter.setItemClickListener((id, title) -> {
            Intent intent = new Intent(this, ShoppingActivity.class);
            intent.putExtra("type", id);
            intent.putExtra("provincename", title);
            startActivity(intent);
        });

        /*myMapView.setOnChoseProvince((provincename, id) -> {
            Intent intent = new Intent(this, ShoppingActivity.class);
            intent.putExtra("type", id);
            intent.putExtra("provincename", provincename);
            startActivity(intent);
        });*/


        iv_image_person.setOnClickListener(view -> {
            if (userInfo == null) {
                startActivitys(LoginActivity.class, 1);
            } else {
                startActivitys(UserInfoActivity.class);
            }
        });

        navigationView.setNavigationItemSelectedListener(item -> {
            if (userInfo == null) {
                startActivitys(LoginActivity.class, 1);
            } else {
                if (item.getTitle().equals("我的订单")) {
                    startActivitys(OrderListActivity.class);
                } else if (item.getTitle().equals("我的商户")) {
                    DialogUtils.dialogRegis(this, "商户端已独立出去，请到应用商城搜索昆仑部落商户版。");
                    DialogUtils.getTv_sure().setOnClickListener(v -> DialogUtils.dismissDialog());
                } else if (item.getTitle().equals("我的购物车")) {
                    startActivitys(ShoppingCarActivity.class);
                } else if (item.getTitle().equals("地址")) {
                    startActivitys(ShowAddressActivity.class);
                } else if (item.getTitle().equals("设置")) {
                    startActivitys(SettingActivity.class);
                } else {
                    ToastUtils.showLongToast(item.getTitle());
                }
            }
            drawerLayout.closeDrawer(navigationView);
            return true;
        });
    }


    private void setColorView() {
        colorView_hashmap = new HashMap<>();
        for (int i = 0; i < ColorChangeHelp.nameStrings.length; i++) {
            String colors[] = ColorChangeHelp.colorStrings[i].split(",");
            String texts[] = ColorChangeHelp.textStrings[i].split(",");
            List<MycolorArea> list = new ArrayList<>();
            for (int j = 0; j < colors.length; j++) {
                MycolorArea c = new MycolorArea();
                c.setColor(Color.parseColor(colors[j]));
                c.setText(texts[j]);
                list.add(c);
            }
            colorView_hashmap.put(ColorChangeHelp.nameStrings[i], list);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showShortToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.isUnsubscribed();
    }
}
